package week02

import "sort"

// 49. 字母异位词分组
// https://leetcode-cn.com/problems/group-anagrams/

// 单词字母排序
func groupAnagrams(strs []string) [][]string {
	var group = make(map[string][]string)
	for _, str := range strs {
		bytes := []byte(str)
		sort.Sort(byteSort(bytes))
		group[string(bytes)] = append(group[string(bytes)], str)
	}
	var ans [][]string
	for _, item := range group {
		ans = append(ans, item)
	}
	return ans
}

type byteSort []byte
func (bs byteSort) Less(i, j int) bool { return bs[i] > bs[j] }
func (bs byteSort) Len() int { return len(bs) }
func (bs byteSort) Swap(i, j int) { bs[i], bs[j] = bs[j], bs[i] }



// 统计每个单词每个字母数量
func groupAnagrams2(strs []string) [][]string {
	var group = make(map[[26]int][]string)
	for _, str := range strs {
		var m = calcLetter(str)
		group[m] = append(group[m], str)
	}
	var ans [][]string
	for _, item := range group {
		ans = append(ans, item)
	}
	return ans
}

// 统计单词每个字母数量
func calcLetter(word string) [26]int {
	var count [26]int
	for _, b := range []byte(word) {
		count[b%26]++
	}
	return count
}